
import {configStoreKey, initBrowserError, Message, MsgType, SyncMethod} from "@/utils/constants";
import {dumpConfigJSON} from "@/utils/config";
import {toRaw} from "vue";
import {browserDriver, config} from "@/store/modules/globals";


if (!browserDriver.sendMessage || !browserDriver.storeObjectToStorage) {
    throw initBrowserError;
}
const sendMessage: Function = browserDriver.sendMessage;
const storeObjectToStorage: Function = browserDriver.storeObjectToStorage;

/**
 * 保存配置
 */
function saveConfig() {
    let json = dumpConfigJSON(config);
    storeObjectToStorage(configStoreKey, json);
    // console.log("saveConfig", json);
}


/**
 * 改变同步服务的同步状态
 * 全局只能存在唯一一个同步方法是同步的服务
 * @param serviceName
 * @param syncMethod
 * @param cronSyncTime
 */
function changeSyncServiceSyncStatus(serviceName: string, syncMethod: SyncMethod, cronSyncTime?: number | null) {
    if (syncMethod == SyncMethod.sync) {
        let syncServiceSettingMap = toRaw(config.syncServiceSettingMap.value);
        for (const [key, syncServiceSetting] of Object.entries(syncServiceSettingMap)) {
            if (key === serviceName) {
                continue
            }
            if (syncServiceSetting.syncMethod.value === SyncMethod.sync) {
                syncServiceSetting.syncMethod.value = SyncMethod.none;
            }
        }
    }
    saveConfig();
    const msg: Message = {
        type: MsgType.updateSyncMethod,
        data: {
            "serviceName": serviceName,
            "syncMethod": syncMethod,
            "cronSyncTime": cronSyncTime
        }
    };
    sendMessage(msg);
}


function changeCronSyncTime(serviceName: string, cronSyncTime: number | null) {
    saveConfig();
    const msg: Message = {
        type: MsgType.updateCronTime,
        data: {
            "serviceName": serviceName,
            "cronSyncTime": cronSyncTime
        }
    };
    sendMessage(msg);
}


export {saveConfig, changeSyncServiceSyncStatus, changeCronSyncTime};
